package com.markhsiu.MiniMQ.model;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.markhsiu.MiniMQ.model.constant.MessageCmdEnum;
import com.markhsiu.MiniMQ.model.constant.MessageSourceEnum;

/**
 * 远程传输消息体
 * @author Mark Hsiu
 *
 */
public  class Message implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final String key_consumerID = "consumerID"; 
	
	private String messageID;//消息ID
	private MessageSourceEnum source;//消息来源
	private MessageSourceEnum target;//消息目标
	private MessageCmdEnum cmd;//消息命令
	private String topic ;//消息主题
	private Map<String, Object> body = new HashMap<>();//消息内容
	private Long timestamp;//时间戳
	
	private static final String default_topic = "topic";
	
	public String getTopic() {
		if(topic == null){
			topic = default_topic;
		}
		return topic;
	}
	public void setTopic(String topic) {
		
		this.topic = topic;
	}
	public String getMessageID() {
		return messageID;
	}
	public void setMessageID(String messageID) {
		this.messageID = messageID;
	}
	 
	 
	public Long getTimestamp() {
		return timestamp;
	}
	public void setTimestamp(Long timestamp) {
		this.timestamp = timestamp;
	}
	public MessageSourceEnum getSource() {
		return source;
	}
	public void setSource(MessageSourceEnum source) {
		this.source = source;
	}
	public MessageSourceEnum getTarget() {
		return target;
	}
	public void setTarget(MessageSourceEnum target) {
		this.target = target;
	} 
	
	public MessageCmdEnum getCmd() {
		return cmd;
	}
	public void setCmd(MessageCmdEnum cmd) {
		this.cmd = cmd;
	}
	
	public  String getBodyString(String key){
		return  (String) body.get(key);
	}
	
	public  Integer getBodyInteger(String key){
		return  (Integer) body.get(key);
	}
	
	public  void setConsumerID(String consumerID){
		body.put(key_consumerID, consumerID);
	}
	
	public  String getConsumerID(){
		return getBodyString(key_consumerID);
	}
	
	public static Message newSuccess(){
		Message message = new ResponseMessage();
		message.setCmd(MessageCmdEnum.SUCCESS); 
		message.setTimestamp(System.currentTimeMillis());
		return message;
	}
	
	public static Message newFail(){
		Message message = new ResponseMessage();
		message.setCmd(MessageCmdEnum.FAIL); 
		message.setTimestamp(System.currentTimeMillis());
		return message;
	}
	
	public static Message newError(){
		Message message = new ResponseMessage();
		message.setCmd(MessageCmdEnum.ERROR); 
		message.setTimestamp(System.currentTimeMillis());
		return message;
	}
	
	@Override
	public String toString(){	
		 
		return String.format("cmd:%s topic:%s  ID:%s  source:%s  target:%s ",
				cmd,
				topic,
				messageID,
				source,
				target);
	}
	
}
